package com.ctyon.watchmanager.ui.fragment;

import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.alibaba.sdk.android.oss.common.utils.OSSUtils;
import com.ctyon.common.event.GetImgEvent;
import com.ctyon.common.util.DataUtil;
import com.ctyon.common.util.GsonUtil;
import com.ctyon.common.util.TSnackbarUtil;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.config.ImageBean;
import com.ctyon.watchmanager.databinding.FragmentCameraBinding;
import com.ctyon.watchmanager.listener.ItemClickListener;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.ctyon.watchmanager.present.CameraPresenter;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.ctyon.watchmanager.ui.adapter.PictureAdapter;
import com.ctyon.watchmanager.util.BytesUtil;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;
import com.previewlibrary.GPreviewBuilder;
import com.previewlibrary.enitity.BaseEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.ctyon.watchmanager.config.OssConfig.endpoint;
import static com.ctyon.watchmanager.config.OssConfig.picture;

/**
 * CreateDate：19-6-25 on 上午9:14
 * Describe:
 * Coder: lee
 */
public class CameraFragment extends BaseFragment {

    public static final String TAG = "CameraFragment";

    private FragmentCameraBinding mBinding;

    private PictureAdapter mAdapter;
    private GridLayoutManager mGridLayoutManager;
    private List<BaseEntity> imgPaths = new ArrayList<>();
    private List<String> imgPathList = new ArrayList<>();

    public static CameraFragment newInstance() {
        final CameraFragment fragment = new CameraFragment();
        final Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        EventBus.getDefault().register(this);
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_camera, container, false);
        mBinding.setCameraPresenter(cameraPresenter);
        mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
        mBinding.pictureRecycler.setLayoutManager(mGridLayoutManager);
        mAdapter = new PictureAdapter(itemClickListener);
        mBinding.pictureRecycler.setAdapter(mAdapter);

        return mBinding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loadImg();
    }

    private final CameraPresenter cameraPresenter = () -> {
        final String method = "takePicture";
        if (NetService.getInstance().isDisable(method)){
            TSnackbarUtil.TSBError(getActivity(), "请稍候...");
            return;
        }
        NetService.getInstance()
                .takePicture(BasicApp.getInstance().getManager().getManagerId(), BasicApp.getInstance().getWatch().getMeid())
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponseEntity>() {
                    @Override
                    public void onSuccess(BaseResponseEntity responseEntity) {
                        Logger.d("onSuccess : " + responseEntity.toString());
                        TSnackbarUtil.TSBSuccess(getActivity(), "操作成功");
                    }

                    @Override
                    public String onOver() {
                        return method;
                    }
                });
    };

    private final ItemClickListener<Integer> itemClickListener = new ItemClickListener<Integer>() {
        @Override
        public void onItemClick(Integer model) {
            Log.e("androidLog","图片position="+model);

            computeBoundsBackward(mGridLayoutManager.findFirstVisibleItemPosition());
            GPreviewBuilder.from(getActivity())
                    .setData(imgPaths)
                    .setSingleFling(true)
                    .setCurrentIndex(model)
                    .setType(GPreviewBuilder.IndicatorType.Number)
                    .start();
        }

        @Override
        public void onBt1Click(Integer model) {
            mAdapter.remove(model);
            deleteImg(model);
        }

    };

    /**
     * 查找信息
     * 从第一个完整可见item逆序遍历，如果初始位置为0，则不执行方法内循环
     */
    private void computeBoundsBackward(int firstCompletelyVisiblePos) {
        for (int i = firstCompletelyVisiblePos;i < imgPaths.size(); i++) {
            View itemView = mGridLayoutManager.findViewByPosition(i);
            Rect bounds = new Rect();
            if (itemView != null) {
                ImageView thumbView = (ImageView) itemView.findViewById(R.id.img);
                thumbView.getGlobalVisibleRect(bounds);
            }
            imgPaths.get(i).setBounds(bounds);
        }
    }

    private void loadImg(){
        final String method = "getImg";
        if (NetService.getInstance().isDisable(method)){
            TSnackbarUtil.TSBError(getActivity(), "请稍候...");
            return;
        }
        NetService.getInstance()
                .getImg(BasicApp.getInstance().getWatch().getMeid())
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponseEntity>() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onSuccess(BaseResponseEntity responseEntity) {
                        Logger.d("onSuccess : " + responseEntity.toString());
                        if (null != responseEntity.data){
                            String data = responseEntity.data.toString();
                            if(!DataUtil.isEmptyOr(data) && data.length() > 2){
                                imgPathList.clear();
                                String str = responseEntity.data.toString().replace("[","").replace("]","");
                                String strs[] = str.split(",");
                                for(String imgPath:strs){
                                    imgPathList.add(imgPath.trim());
                                }
                                mAdapter.setPictureList(imgPathList);
                                mBinding.pictureRecycler.smoothScrollToPosition(imgPathList.size()-1);

                                BasicApp.getInstance().getAppExecutors().networkIO().execute(()->{
                                    imgPaths.clear();
                                    for (int i = 0; i < imgPathList.size(); i++) {
                                        BaseEntity entity = new BaseEntity();
                                        entity.setUrl(endpoint.replace("http://", "https://ctyon.") + "/" + picture + "socketclient" + imgPathList.get(i) + ".jpg");
                                        imgPaths.add(entity);
                                    }

                                });
                            }
                        }
                    }

                    @Override
                    public String onOver() {
                        return method;
                    }

                });
    }

    private void deleteImg(int index){
        final String method = "delImg";
        if (NetService.getInstance().isDisable(method)){
            TSnackbarUtil.TSBError(getActivity(), "请稍候...");
            return;
        }
        NetService.getInstance()
                .delImg(BasicApp.getInstance().getWatch().getMeid(), imgPathList.get(index))
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponseEntity>() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onSuccess(BaseResponseEntity responseEntity) {
                        Logger.d("onSuccess : " + responseEntity.toString());
                        TSnackbarUtil.TSBSuccess(getActivity(), "删除成功");

                        Log.d(LTAG,"imgPathList size = "+imgPathList.size());
                        Log.d(LTAG, "imgPaths size = " + imgPaths.size());
                        imgPathList.remove(index);
                        imgPaths.remove(index);
                    }

                    @Override
                    public String onOver() {
                        return method;
                    }

                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void getImageEvent(GetImgEvent getImgEvent){
        TSnackbarUtil.TSBSuccess(getActivity(), "收到照片");
        loadImg();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
